package com.suray.wcs.web.system.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.suray.basic.wcs.plc.pojo.Robot;
import com.suray.basic.wcs.plc.pojo.TaskSend;
import com.suray.commin.annotation.InterfaceLog;
import com.suray.commin.core.controller.ResponseData;
import com.suray.wcs.service.enums.MachineTaskStatus;
import com.suray.wcs.service.enums.TaskStatusGroup;
import com.suray.wcs.service.init.SystemInit;
import com.suray.wcs.service.init.device.DeviceManager;
import com.suray.wcs.service.pojo.BaseEum;
import com.suray.wcs.service.robot.ToRobot;
import com.suray.wcs.service.system.bo.PageBO;
import com.suray.wcs.service.system.bo.QueryMachineTasksBO;
import com.suray.wcs.service.system.entity.MachineTaskDB;
import com.suray.wcs.service.system.service.MachineTaskService;
import com.suray.wcs.service.wmsconnect.ToWms;
import com.suray.wcs.web.system.request.ChangeMachineTaskRequest;
import com.suray.wcs.web.system.request.QueryMachineTasksRequest;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/machineTask")
@CrossOrigin(value = "*", allowCredentials = "true")
public class MachineTaskController {
    private Logger log = LoggerFactory.getLogger(MachineTaskController.class);

    @Autowired
    private MachineTaskService machineTaskService;

    @Autowired
    private ToWms toWms;

    /**
     * 查询AGV任务状态枚举
     *
     * @return
     */
    @ApiOperation(value = "查询机械臂任务状态枚举")
    @InterfaceLog(value = "查询AGV任务状态枚举信息")
    @GetMapping("/getMachineTaskStatus")
    public ResponseData getMachineTaskStatus() {
        List<BaseEum> pro = getMachineTaskStatusEnums();
        return ResponseData.success("查询成功", pro);
    }

    /**
     * 获取枚举类型
     *
     * @return
     */
    private List<BaseEum> getMachineTaskStatusEnums() {
        List<MachineTaskStatus> machineTaskPros = (Arrays.asList(MachineTaskStatus.values()));
        List<BaseEum> taskProList = new ArrayList<BaseEum>();
        for (MachineTaskStatus pro : machineTaskPros) {
            taskProList.add(new BaseEum(pro.getValue(), pro.toString()));
        }
        return taskProList;
    }

    @PutMapping(value = "/changeMachineTaskInfo/{id}")
    @ApiOperation("修改机械臂任务信息")
    @InterfaceLog(value = "修改机械臂任务信息")
    public ResponseData changeMachineTaskInfo(@PathVariable("id") Integer id, @RequestBody ChangeMachineTaskRequest request) {
        if (id == null || id < 1) {
            return ResponseData.error("任务不存在");
        }
        if (request == null) {
            return ResponseData.error("请求参数不可为空");
        }
        if (request != null && request.checkHasEmpty()) {
            return ResponseData.error("请求参数有误");
        }
        MachineTaskDB machineTaskDB = machineTaskService.queryMachineTaskInfoById(id);
        if (machineTaskDB == null) {
            return ResponseData.error("任务Id不存在");
        }
        machineTaskDB.setStartStation(request.getStartStation());
        machineTaskDB.setEndStation(request.getEndStation());
        machineTaskDB.setTaskStatus(request.getTaskStatus());

        int success = machineTaskService.updateMachineTaskInfo(machineTaskDB);
        if (success == 1) {
            return ResponseData.success("任务修改成功");
        } else {
            return ResponseData.error("任务修改失败");
        }
    }

    @DeleteMapping(value = "/deleteMachineTask")
    @ApiOperation("根据勾选删除机械臂任务")
    @InterfaceLog(value = "删除机械臂任务")
    public ResponseData deleteMachineTask(@RequestBody List<Integer> taskId) {
        if (taskId == null || taskId.size() == 0) {
            return ResponseData.error("请勾选删除项");
        } else {
            int success = machineTaskService.deleteMachineTasks(taskId);
            if (success > 0) {
                return ResponseData.success("任务删除完成");
            } else {
                return ResponseData.error("所选任务号不存在");
            }
        }
    }

    @GetMapping(value = "/queryTaskStatusGroup")
    @ApiOperation("机械臂任务完成下拉选项")
    @InterfaceLog("机械臂任务分组下拉框")
    public ResponseData queryTaskStatusGroup() {
        List<TaskStatusGroup> taskStatusGroups = (Arrays.asList(TaskStatusGroup.values()));
        List<BaseEum> taskTypeList = new ArrayList<BaseEum>();
        for (TaskStatusGroup item : taskStatusGroups) {
            taskTypeList.add(new BaseEum(item.getProgressNum(), item.toString()));
        }
        if (taskTypeList.size() > 0 && taskTypeList != null) {
            return ResponseData.success("查询完成", taskTypeList);
        } else {
            return ResponseData.error("此任务类型没有信息");
        }
    }

    /**
     * 查找接口
     *
     * @throws Exception
     */
    /**
     * 查找接口
     *
     * @throws Exception
     */
    @InterfaceLog("机械手任务条件查询")
    @GetMapping(value = "/queryMachineTaskDB")
    @ResponseBody
    @ApiOperation("按条件查找机械臂任务")
    public ResponseData queryMachineTaskDB(QueryMachineTasksRequest request) {
        QueryMachineTasksBO queryMachineTasksBO = new QueryMachineTasksBO();
        BeanUtils.copyProperties(request, queryMachineTasksBO);
        if (request.getCurPage() != null && request.getPageSize() != null) {
            PageBO pageBO = new PageBO();
            pageBO.setCurrentPage(request.getCurPage().longValue());
            pageBO.setPageSize(request.getPageSize().longValue());
            queryMachineTasksBO.setPageBO(pageBO);
        }
        IPage<MachineTaskDB> machineTasks = machineTaskService.queryMachineTasks(queryMachineTasksBO);
        return ResponseData.success("查询成功", machineTasks);
    }

    /**
     * 机械臂任务重新下发
     *
     * @throws Exception
     */
    @InterfaceLog("机械臂任务重新下发")
    @PostMapping("/reSendTask")
    @ResponseBody
    @ApiOperation("机械臂任务重新下发")
    public ResponseData reSendTask(@RequestParam Map<String, String> mapMsg) {
        if (mapMsg == null || mapMsg.isEmpty()) {
            return ResponseData.error("前端传入参数错误");
        }
        try {
            Integer taskId = Integer.parseInt(mapMsg.get("taskId"));

            MachineTaskDB machineTaskDB = machineTaskService.queryMachineTaskInfoById(taskId);
            if (machineTaskDB == null) {
                return ResponseData.error("任务：" + taskId + "在数据库中不存在");
            }
            // 已完成的任务不可进行重复下发
            if (MachineTaskStatus.TASK_FINISH.equals(machineTaskDB.getTaskStatus())
                    || MachineTaskStatus.SENT.equals(machineTaskDB.getTaskStatus())) {
                return ResponseData.error("已下发或任务完成状态的机械臂任务不可进行重新下发！");
            }

            // 根据机械臂编号获取对应机械臂的对象
            Robot robot = DeviceManager.getByRobotNo(machineTaskDB.getMachineNo());
            // 根据机械臂对象获取操作机械臂对象
            ToRobot toRobot = ToRobot.getInstance(robot);
            // 初始化机械臂任务对象
            TaskSend taskSend = new TaskSend(machineTaskDB.getTaskId(), machineTaskDB.getProductType(), machineTaskDB.getStartStation(), machineTaskDB.getEndStation(), machineTaskDB.getCargoCount());
            long curtime = System.currentTimeMillis();
            robot.getRobotHeart().getTaskSendCommand().offer(taskSend);
            taskSend.setTaskSendTaskNo(toRobot.getAutoIncrementNum());
            //
            if (toRobot.resReceiveResult(taskSend, curtime)) {
                // 更新机械臂任务为已下发
                machineTaskDB.setTaskStatus(MachineTaskStatus.SENT.getValue());
                machineTaskService.updateMachineTaskInfo(machineTaskDB);
                return ResponseData.success("机械臂任务重新下发成功");
            }
            return ResponseData.error("机械臂任务重新下发失败");
        } catch (Exception e) {
            log.error("机械臂任务重新下发异常，原因：", e);
            return ResponseData.error("机械臂任务重新下发异常");
        }
    }
}
